/*
 * Team Name: Team Sasquatch
 * Cody Sharff
 * Anthony Rios
 * Prince Kishore
 * Travis Drake
 */

package gui;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Observable;
import java.util.Scanner;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SpringLayout;

import model.Auction;
import model.User;
import model.UserType;

/**
 * This class contains a panel that allows an AuctionCentral
 * employee or NPO to create an auction.
 * 
 * @author Anthony Rios
 *
 */
public class AddAuctionGUI extends Observable {
	
	public static final String CANCEL = "Cancel";
	
	private final JPanel my_item_panel;
	
	private final String my_item_info[] = new String[7];
	
	private final List<JTextField> my_text_field_list = new ArrayList<JTextField>();
		
	private final JTextField my_auction_npo = new JTextField(20);
		
	private final JTextField my_contact_person = new JTextField(20);

	private final JTextField my_contact_phone = new JTextField(20);
	
	private final JTextField my_auction_central_intake_person = new JTextField(20);
	
	private final JTextField my_auction_date = new JTextField(20);
	
	private final JTextField my_auction_start_time = new JTextField(20);
	
	private final JTextField my_auction_duration = new JTextField(20);
		
	private final JTextArea my_comment_section = new JTextArea(10,100);
	
	private final JButton my_submit_button = new JButton("Submit");
	
	private final JButton my_cancel_button = new JButton("Cancel");

    private User my_cur_user;
	
	/**
	 * The constructor for this GUI.  Creates an observable panel.  To get the panel
	 * use the getPanel method.
	 */
	public AddAuctionGUI(User the_cur_user) {
		my_item_panel = new JPanel();
        my_cur_user = the_cur_user;
		my_item_panel.setLayout(new BorderLayout());
		my_comment_section.setSize(800, 600);
		my_submit_button.addActionListener(new ButtonListener());
		my_cancel_button.addActionListener(new ButtonListener());
		createAuctionInfoArray();
		createTextFieldArray();
		layoutComponents();
		my_item_panel.setVisible(true);
		my_item_panel.setName("Add Auction");
		if (my_cur_user.getType() == UserType.NPO)
		{
		    my_auction_central_intake_person.setVisible(false);
		}
	}

	/**
	 * Adds the auction GUI
     * @param the_obj
     * 
     * @requires the_cur_user != null
     * @requires the_obj != null
     * @requires the_obj to be a valid date
     * @ensures adds auction gui
     */
    public AddAuctionGUI(User the_cur_user, Calendar the_obj)
    {
        this(the_cur_user);
        setAuctionDate(the_obj);
        if (my_cur_user.getType() == UserType.NPO) 
        {
            my_auction_npo.setText(my_cur_user.getName());
            my_auction_npo.setEditable(false);
        }
    }

    public JPanel getPanel() {
		return my_item_panel;
	}

	/**
	 * layout all the buttons and text fields in the proper format by using
	 * an assortment of panels.
	 */
	public void layoutComponents() {
		final JPanel spring_layout = new JPanel();
		spring_layout.setLayout(new SpringLayout());
        for (int i = 0; i < my_text_field_list.size(); i++) {

            if (i == 3 && my_cur_user.getType() == UserType.NPO)
            {
                
            } else {

                JLabel label = new JLabel(my_item_info[i]);
                spring_layout.add(label);
                spring_layout.add(my_text_field_list.get(i));
            }
        }
        JLabel comment_label = new JLabel("Comments");
        spring_layout.add(comment_label);
        spring_layout.add(my_comment_section);
        if (my_cur_user.getType() == UserType.NPO)
        {
            SpringUtilities.makeCompactGrid(spring_layout,
                        7, 2,        //rows, cols
                        6, 6,        //initX, initY
                        6, 6);       //xPad, yPad
        } else {
            SpringUtilities.makeCompactGrid(spring_layout,
                        8, 2,        //rows, cols
                        6, 6,        //initX, initY
                        6, 6);       //xPad, yPad
        }
        my_item_panel.add(spring_layout, BorderLayout.CENTER);
        JPanel south_panel = new JPanel(new FlowLayout());
        south_panel.add(my_cancel_button);
        south_panel.add(my_submit_button);
        my_item_panel.add(south_panel, BorderLayout.SOUTH);
	}
	
	/**
	 * displays an error if any of the text fields are empty.
	 */
	public void displayError()
    {
        JOptionPane.showMessageDialog(null, "One or more text fields are empty");
    }
	
    /**
     * Sets the Auction date.
     */
	public void setAuctionDate(Calendar the_date) {
  	  my_auction_date.setText((the_date.get(Calendar.MONTH) + 1) + "/" + the_date.get(Calendar.DAY_OF_MONTH) + "/" + the_date.get(Calendar.YEAR));
  	  my_auction_date.setEditable(false);
    }
	
	/**
	 * creates an array of the text fields.
	 */
	private void createTextFieldArray() {
		my_text_field_list.add(my_auction_npo);
		my_text_field_list.add(my_contact_person);
		my_text_field_list.add(my_contact_phone);        
	
        my_text_field_list.add(my_auction_central_intake_person);
        
		my_text_field_list.add(my_auction_date);
		my_text_field_list.add(my_auction_start_time);
		my_text_field_list.add(my_auction_duration);
	}

	/**
	 * helper method to create the array that holds the strings that explain
	 * what should be entered in each text field.
	 */
	private void createAuctionInfoArray() {
		my_item_info [0] = "Auction NPO";
		my_item_info [1] = "Contact person";
		my_item_info [2] = "Contact's phone (ex: 2539210693)";
		my_item_info [3] = "AuctionCentral intake person";
		my_item_info [4] = "Auction date (mm/dd/yyyy)";
		my_item_info [5] = "Auction start time (24h, hh:mm)";
		my_item_info [6] = "Auction duration (in hours)";
	}
	
    /**
     * Action listeners for the submit and cancel button.
     * 
     * @author Anthony Rios
     * @version 05-27-12
     */
    protected class ButtonListener implements ActionListener
    {
      /**
       * checks to see if the_event is the cancel button or submit button.
       * If its the submit button the fields are all check to make sure they are not
       * empty.  If they are not empty a new Auction is created and sent to the observer.
       * If the cancel button is clicked a string "cancel" is simply sent to the observer.
       */
      @Override
      public void actionPerformed(final ActionEvent the_event)
      {
    	  if (the_event.getActionCommand().equals(my_submit_button.getActionCommand())) {
    		  boolean empty = false;
    		  for (int i = 0; i < my_text_field_list.size(); i++) {
    			  String field_text = my_text_field_list.get(i).getText();
    			  if (field_text.isEmpty() && !(i == 3)) {
    				  displayError();
    				  empty = true;
    				  break;
    			  }
    		  }
    		  if (!empty) {
    			  int auction_id_number = Auction.next_auction_id;
    			  Auction.next_auction_id++;
    			  String npo = my_auction_npo.getText();
    			  String contact_person = my_contact_person.getText();
    			  long contact_number = Long.parseLong(my_contact_phone.getText());
    			  String intake_person = my_auction_central_intake_person.getText();
    			  GregorianCalendar auction_date = makeCalendarDay();
    			  int auction_duration = (int) (Double.parseDouble(my_auction_duration.getText()) * 60);
    			  String comment = my_comment_section.getText(); 
    			  Auction new_auction = new Auction(auction_id_number, npo, 
    					  contact_person, contact_number, intake_person, 
    					  auction_date, auction_duration, comment);
    			  setChanged();
    	       	  notifyObservers(new_auction);
    		  }
    	  }
    	  else if (the_event.getActionCommand().equals(my_cancel_button.getActionCommand())) {
    		  setChanged();
    		  notifyObservers(CANCEL);
    	  }
       }

    /**
     * Parses out the date field in the gui and creates a GregorianCalendar
     * date from it.
     */
	private GregorianCalendar makeCalendarDay() {
		String auction_date = my_auction_date.getText();
		Scanner temp_parser = new Scanner(auction_date);
		temp_parser.useDelimiter("/");
		int month = temp_parser.nextInt() - 1;
		int day = temp_parser.nextInt();
		int year = temp_parser.nextInt();
		Scanner time_parser = new Scanner(my_auction_start_time.getText());
		time_parser.useDelimiter(":");
		int hour = time_parser.nextInt();
		int minute = time_parser.nextInt();
		return new GregorianCalendar(year, month, day, hour, minute);
	}
    }
}
